use cmake::Config;
use std::env;

fn main() {
    build_and_link();

    // Generate bindings
    bindgen::Builder::default()
        .clang_args(&["-I./libsrtp/include"])
        .header("libsrtp/include/srtp.h")
        .allowlist_function("(srtp|SRTP|srtcp|SRTCP)_.*")
        .allowlist_type("(srtp|SRTP|srtcp|SRTCP)_.*")
        .allowlist_var("(srtp|SRTP|srtcp|SRTCP)_.*")
        .derive_partialeq(true)
        .derive_eq(true)
        .generate()
        .unwrap()
        .write_to_file(format!("{}/bindings.rs", env::var("OUT_DIR").unwrap()))
        .unwrap();
}

fn build_and_link() {
    let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
    
    let dst = if target_os == "windows" {
        // Windows configuration with vcpkg
        let vcpkg_root = env::var("VCPKG_ROOT")
            .unwrap_or_else(|_| "C:/Users/yubo/RustroverProjects/vcpkg".to_string());
        
        let openssl_root = format!("{}/installed/x64-windows-static-md", vcpkg_root);
        let openssl_lib_dir = format!("{}/lib", openssl_root);
        let openssl_include_dir = format!("{}/include", openssl_root);

        Config::new("libsrtp")
            .define("ENABLE_OPENSSL", "ON")
            .define("LIBSRTP_TEST_APPS", "OFF")
            .define("ENABLE_WARNINGS_AS_ERRORS", "OFF")
            .define("OPENSSL_ROOT_DIR", &openssl_root)
            .define("OPENSSL_CRYPTO_LIBRARY", format!("{}/libcrypto.lib", openssl_lib_dir))
            .define("OPENSSL_SSL_LIBRARY", format!("{}/libssl.lib", openssl_lib_dir))
            .define("OPENSSL_INCLUDE_DIR", &openssl_include_dir)
            .build()
    } else {
        // Linux/macOS configuration using system OpenSSL
        Config::new("libsrtp")
            .define("ENABLE_OPENSSL", "ON")
            .define("LIBSRTP_TEST_APPS", "OFF")
            .define("ENABLE_WARNINGS_AS_ERRORS", "OFF")
            .build()
    };

    println!(
        "cargo:rustc-link-search=native={}",
        dst.join("lib").display()
    );
    println!("cargo:rustc-link-lib=static=srtp2");
    
    // Link NSS libraries for Linux
    if target_os != "windows" {
        println!("cargo:rustc-link-lib=nss3");
        println!("cargo:rustc-link-lib=ssl3");
        println!("cargo:rustc-link-lib=smime3");
        println!("cargo:rustc-link-lib=nspr4");
    }
}
